package cn.smxy.search.service.impl;

import cn.smxy.client.UserClient;
import cn.smxy.param.PlantSearchParam;
import cn.smxy.pojo.Plant;
import cn.smxy.pojo.User;
import cn.smxy.search.service.SearchService;
import cn.smxy.util.R;
import cn.smxy.vo.PlantVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private UserClient userClient;

    /**
     * 植物搜索
     *
     * @param plantSearchParam
     * @return
     */
    @Override
    public R plantList(PlantSearchParam plantSearchParam) throws JsonProcessingException {

        SearchRequest searchRequest = new SearchRequest("plant");
        if (StringUtils.isEmpty(plantSearchParam.getSearch())) {
            // 如果为null,查询全部
            searchRequest.source().query(QueryBuilders.matchAllQuery());
        } else {
            // 不为null all字段查询
            searchRequest.source().query(QueryBuilders.matchQuery("all", plantSearchParam.getSearch()));
        }

        // 设置分页参数
        searchRequest.source().from(plantSearchParam.getFrom());
        searchRequest.source().size(plantSearchParam.getSize());
        SearchResponse response = null;
        try {
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 结果集解析
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;

        SearchHit[] items = hits.getHits();

        List<PlantVo> plantVoList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        for (SearchHit item : items) {
            String json = item.getSourceAsString();
            Plant plant = objectMapper.readValue(json, Plant.class);
            PlantVo plantVo = new PlantVo(plant);
            User user = userClient.getUserName(plantVo.getUserId());
            plantVo.setUserName(user.getUserName());
            plantVo.setUserPhoto(user.getUserPhoto());
            plantVoList.add(plantVo);
        }
        log.info("SearchServiceImpl.plantList业务结束，结果为:{}", "查询成功");
        return R.ok(null, plantVoList, total);
    }
}
